package servlet;

import bean.AllMessage;
import bean.Message;
import bean.PageBean;
import dao.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.JsonWrapper;
import util.ResponseUtil;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 消息功能servlet
 *
 * @author 邓晴予
 */
public class MessageServlet extends HttpServlet {
    private MessageDao messageDao = new MessageDao();
    private ActivityDao activityDao = new ActivityDao();
    private AdviceDao adviceDao = new AdviceDao();
    private AllMessageDao allMessageDao = new AllMessageDao();
    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String type = req.getParameter("type");

        if ("getAllMessage".equals(type)) {
//			获取我消息
            this.getAllMessage(req, resp);
        } else if ("getCount".equals(type)) {
//			获取消息数目
            this.getMessageCount(req, resp);
        } else if ("getDetail".equals(type)) {
//			查看消息详情
            this.getDetail(req, resp);
        }
    }

    /**
     * 查看消息详情
     *
     * @param req
     * @param resp
     * @throws IOException
     * @author 邓晴予
     */
    private void getDetail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userId = req.getParameter("userId");
        String messageId = req.getParameter("messageId");
        JsonWrapper result = new JsonWrapper();
        try {
//      String head = messageId.substring(0, 1);
/*      if ("1".equals(head)) {
//				消息是管理员对骑行用户发的activity请求的反馈
        List<Object> activities = activityDao.activityList(null, new Activity(messageId), null, null, null, null, null, null);
//				把消息状态改为骑行用户已读
        if (activities.size() == 1) {
          Activity resultActivity = (Activity) activities.get(0);
          Activity activity = new Activity();
          activity.setActivityId(messageId);
          if ("2".equals(resultActivity.getStatus())) {
            activity.setStatus("4");
            resultActivity.setStatus("4");
          } else if ("3".equals(resultActivity.getStatus())) {
            activity.setStatus("5");
            resultActivity.setStatus("5");
          }
          activityDao.activityModify(activity);

          AllMessage allMessage = allMessageDao.parseFromActivity(activity);
          if (allMessage != null) {
            JSONObject jsonObject = JsonWrapper.parseFromObject(allMessage);
            result.setDataEntry("message", jsonObject);
            result.setStatus(200);
            result.setMsg("success");
          }
        }
      } else if ("2".equals(head)) {
//				消息是管理员对骑行用户发的advice请求的反馈
        Advice advice = new Advice();
        advice.setAdviseId(messageId);
        advice.setStatus("3");
        adviceDao.adviceModify(advice);
        List<Object> advices = adviceDao.adviceList(null, new Advice(messageId), null, null, null, null);
//				把消息状态改为已读
        if (advices.size() == 1) {
          AllMessage allMessage = allMessageDao.parseFromAdvice((Advice) advices.get(0));
          if (allMessage != null) {
            JSONObject jsonObject = JsonWrapper.parseFromObject(allMessage);
            result.setDataEntry("message", jsonObject);
            result.setStatus(200);
            result.setMsg("success");
          }
        }
      } else */
      /*if ("3".equals(head)) {*/
//				消息是骑行用户之间的私信
//				把消息设为已读
            messageDao.changeStatus(1, messageId);
            List<Object> messages = messageDao.messageList(null, new Message(messageId));
            if (messages.size() == 1) {
                AllMessage allMessage = allMessageDao.parseFromMessage((Message) messages.get(0));
                if (allMessage != null) {
                    JSONObject jsonObject = JsonWrapper.parseFromObject(allMessage);
                    result.setDataEntry("message", jsonObject);
                    result.setStatus(200);
                    result.setMsg("success");
                }
            }
/*      } else {
        return;
      }*/
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(401);
            result.setMsg("failed");
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 获取我的消息个数
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    private void getMessageCount(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userId = req.getParameter("userId");
        JsonWrapper result = new JsonWrapper();

        try {
            int messageCount = messageDao.messageCount(new Message(userId, "0"));
//			int activityCount = activityDao.activityCount(new Activity(userId, "2"), null, null, null, null, null, null)
//					+activityDao.activityCount(new Activity(userId, "3"), null, null, null, null, null, null);
//			int adviceCount = adviceDao.adviceCount(new Advice(userId, "2"), null, null, null, null);
//			int allCount = messageCount+activityCount+adviceCount;
            result.setDataEntry("messageNumber", messageCount);
            result.setStatus(200);
            result.setMsg("success");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(401);
            result.setMsg("failed");
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 发送消息
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("userId");  //发件人id
        String content = req.getParameter("content");  //发送的消息内容
        String phone = req.getParameter("phone");  //收件人手机号
        JsonWrapper result = new JsonWrapper();
        Message message;
        try {
            message = new Message("", userId, userDao.getUserIdByPhone(phone), content, "", "");
            boolean isSuccess = messageDao.messageAdd(message);
            if (isSuccess) {
//				添加成功
                result.setStatus(200);
                result.setMsg("success");
            } else {
//				添加失败
                result.setStatus(404);
                result.setMsg("failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(401);
            result.setMsg("failed");
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 获取我的未读消息，包括activity的管理员反馈、advice的管理员反馈、骑行用户的私信
     *
     * @param req
     * @param resp
     * @return
     * @throws IOException
     */
    private void getAllMessage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userId = req.getParameter("userId");
        String startStr = req.getParameter("start");  //当前页
        String pagesizeStr = req.getParameter("pagesize");  //页记录数
        JsonWrapper result = new JsonWrapper();

        int start = 0;
        int pagesize = 0;
        try {
            if (!StringUtil.isEmpty(startStr)) {
                start = Integer.parseInt(startStr);
            }
            if (!StringUtil.isEmpty(pagesizeStr)) {
                pagesize = Integer.parseInt(pagesizeStr);
            }
        } catch (NumberFormatException exp) {
            result.setStatus(401);
            result.setMsg("failed");
        }
        PageBean pageBean = new PageBean(start, pagesize);

        try {
            //		获取骑行用户未读私信
            List<Object> resultMessage = messageDao.messageList(null, new Message(userId, "0"));
//
//      Activity activity = new Activity();
//      activity.setUserId(userId);
//      //		获取骑行用户发起的活动
//      List<Object> resultActivity = activityDao.activityList(null, activity, null, null, null, null, null, null);
//      Advice advice = new Advice();
//      advice.setCreator(userId);
//      //		获取骑行用户发出的建议
//      List<Object> resultAdvice = adviceDao.adviceList(null, advice, null, null, null, null);

            //		将advice、activity、message转换成AllMessage的格式
//      List<AllMessage> allMessage = allMessageDao.parse(resultMessage, resultActivity, resultAdvice);
            List<AllMessage> allMessage = allMessageDao.parseFromMessages(resultMessage);
            List<AllMessage> resultAllMessage = allMessageDao.getPage(allMessage, pageBean);

            result.setStatus(200);
            result.setMsg("success");

            JSONArray jsonArray = new JSONArray();
            for (Object single : resultAllMessage) {
                JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                jsonArray.add(jsonObject);
            }
            result.setDataJsonArray("values", jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(401);
            result.setMsg("failed");
        }
        ResponseUtil.write(resp, result.get());
    }
}
